/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.gui;

import javax.swing.*;
import java.awt.*;
import java.awt.image.ImageObserver;

public class JImage extends JPanel {

	private Image image = null;

	public JImage(Image image) {
		setImage(image);
	}

	public void setImage(Image image) {
		this.image = image;
		if (image!=null) {
			setPreferredSize(new Dimension(image.getWidth(null),image.getHeight(null)));
		}
		repaint();
	}

	public Image getImage(){
		return image;
	}

	public void paint(Graphics g) {
		super.paint(g);
		Graphics2D g2=(Graphics2D)g;
		if (image != null) {
			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
			int w=getWidth(),h=getHeight();
			int iw=image.getWidth(null),ih=image.getHeight(null);
			double wr=((double)iw)/w;
			double hr=((double)ih)/h;
			double r=0;
			if (wr>hr) {
				r=wr;
			} else {
				r=hr;
			}
			g.drawImage(
				image,
				(w-(int)(iw/r))/2,
				(h-(int)(ih/r))/2,
				(int)(iw/r),
				(int)(ih/r),
				(ImageObserver)null
			);
		}
	}
}

